<template>
    <div class="order-container">
        <!-- 顶部导航 -->
        <div class="top-nav">
            <button class="back-btn" @click="goBack">返回</button>
            <div class="welcome">小淘商城 - 确认订单</div>
        </div>

        <div class="order-content">
            <!-- 收货地址 -->
            <div class="section address-section">
                <div class="section-header">
                    <h3>收货地址</h3>
                    <el-button type="primary" size="small" @click="showAddressDialog = true">新增地址</el-button>
                </div>
                <div class="address-list">
                    <div v-for="address in addresses" :key="address.id" class="address-item"
                        :class="{ active: selectedAddress && selectedAddress.id === address.id }"
                        @click="selectAddress(address)"> <!-- 修改这里，添加 selectedAddress && -->
                        <div class="address-info">
                            <div class="address-main">
                                <span class="receiver">{{ address.receiverName }}</span>
                                <span class="phone">{{ address.receiverPhone }}</span>
                                <span v-if="address.isDefault" class="default-tag">默认</span>
                            </div>
                            <div class="address-detail">
                                {{ address.province }}{{ address.city }}{{ address.district }} {{ address.detailAddress
                                }}
                            </div>
                        </div>
                        <div class="address-actions">
                            <el-button type="text" @click.stop="editAddress(address)">编辑</el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品信息 -->
            <div class="section products-section">
                <div class="section-header">
                    <h3>商品信息</h3>
                </div>
                <div class="products-list">
                    <div v-for="item in orderItems" :key="item.productId" class="product-item">
                        <div class="product-image">
                            <img :src="item.imageUrl" :alt="item.name" />
                        </div>
                        <div class="product-details">
                            <div class="product-name">{{ item.name }}</div>
                            <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
                        </div>
                        <div class="product-quantity">x{{ item.quantity }}</div>
                        <div class="product-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
                    </div>
                </div>
            </div>

            <!-- 订单总结 -->
            <div class="section summary-section">
                <div class="section-header">
                    <h3>订单总结</h3>
                </div>
                <div class="order-summary">
                    <!-- 显示优惠券信息 -->
                    <div v-if="orderDetail && orderDetail.couponNames && orderDetail.couponNames.length > 0" class="summary-row">
                        <span>使用优惠券</span>
                        <span>{{ orderDetail.couponNames.join(', ') }}</span>
                    </div>
                    <div class="summary-row">
                        <span>商品总价</span>
                        <span>¥{{ originalTotal.toFixed(2) }}</span>
                    </div>
                    <div v-if="couponDiscount > 0" class="summary-row">
                        <span>优惠金额</span>
                        <span>-¥{{ couponDiscount.toFixed(2) }}</span>
                    </div>
                    <div class="summary-row">
                        <span>运费</span>
                        <span>
                            <span style="text-decoration: line-through; color: #999;">¥8.00</span>
                            <span>¥0.00</span>
                        </span>
                    </div>
                    <div class="summary-row total">
                        <span>总计</span>
                        <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
                    </div>
                </div>
            </div>

            <!-- 提交订单 -->
            <div class="submit-section">
                <el-button type="danger" size="large" :loading="isSubmitting" @click="submitOrder">
                    提交订单
                </el-button>
            </div>
        </div>

        <!-- 地址对话框 -->
        <el-dialog v-model="showAddressDialog" :title="editingAddress ? '编辑地址' : '新增地址'" width="500px">
            <el-form :model="addressForm" label-width="80px">
                <el-form-item label="收货人">
                    <el-input v-model="addressForm.receiverName" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="addressForm.receiverPhone" />
                </el-form-item>
                <el-form-item label="地区">
                    <el-cascader v-model="selectedRegion" :options="regionOptions" :props="cascaderProps"
                        @change="handleRegionChange" style="width: 100%" />
                </el-form-item>
                <el-form-item label="详细地址">
                    <el-input v-model="addressForm.detailAddress" type="textarea" />
                </el-form-item>
                <el-form-item label="设为默认">
                    <el-switch v-model="addressForm.isDefault" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddressDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveAddress">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { CartItemResponse } from '@/type/cart'
import type { UserAddressType } from '@/type/user'
import { useProfileStore } from '@/store/profile'
import { getProductDetail } from '@/api/product'
import { getProvinces, getCities, getdistricts, getAddresses } from '@/api/profile'
import orderApi, { OrderResponse } from '@/api/order'
import payApi from '@/api/pay'
import promotionApi from '@/api/promotion'

// 移除 extends CartItemResponse，直接定义我们需要的字段
interface OrderItem {
    productId: number
    name: string
    imageUrl: string
    price: number
    quantity: number
    selected: boolean
}

const route = useRoute()
const router = useRouter()

// 数据状态
const addresses = ref<UserAddressType[]>([])
const selectedAddress = ref<UserAddressType | null>(null)
const orderItems = ref<OrderItem[]>([])
const isSubmitting = ref(false)
const orderDetail = ref<OrderResponse & { couponNames?: string[] } | null>(null)

// 地址表单相关
const showAddressDialog = ref(false)
const editingAddress = ref<UserAddressType | null>(null)
const addressForm = ref<UserAddressType>({
    id: 0,
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
})
const selectedRegion = ref<number[]>([])
const regionOptions = ref<Array<{
    id: number;
    name: string;
    children: any[];
}>>([])

// 添加一个新的ref来存储优惠券折扣金额
const couponDiscount = ref(0)


// 计算属性
const originalTotal = computed(() => {
    return orderItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

const shippingFee = computed(() => {
    return originalTotal.value >= 88 ? 0 : 8 // 满88免运费
})

// 修改totalAmount计算属性，减去优惠券折扣
const totalAmount = computed(() => {
    const discountedTotal = originalTotal.value - couponDiscount.value
    return Math.max(discountedTotal, 0) // 确保不会出现负数
})

// 级联选择器配置
const cascaderProps = {
    value: 'id',
    label: 'name',
    children: 'children',
    lazy: true,
    lazyLoad: async (node: any, resolve: any) => {
        const { level, value } = node;
        let nodes = [];

        try {
            if (level === 0) {
                // 加载省份
                const res = await getProvinces();
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    children: []
                }));
            } else if (level === 1) {
                // 加载城市
                const res = await getCities(value);
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    children: []
                }));
            } else if (level === 2) {
                // 加载区县
                const res = await getdistricts(value);
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    leaf: true
                }));
            }
        } catch (error) {
            ElMessage.error('地区数据加载失败');
        }

        resolve(nodes);
    }
}

// 处理地区选择变化
const handleRegionChange = (value: number[]) => {
    if (!value || value.length !== 3) {
        addressForm.value.province = '';
        addressForm.value.city = '';
        addressForm.value.district = '';
        return;
    }

    // 获取选中的省市区名称
    let provinceName = '';
    let cityName = '';
    let districtName = '';

    const findNameById = (options: any[], id: number): string => {
        const item = options.find((opt) => opt.id === id);
        return item ? item.name : '';
    };

    // 省份名称
    provinceName = findNameById(regionOptions.value, value[0]);

    // 城市名称
    const cityOptions = regionOptions.value.find((opt: any) => opt.id === value[0])?.children || [];
    cityName = findNameById(cityOptions, value[1]);

    // 区县名称
    const districtOptions = cityOptions.find((opt: any) => opt.id === value[1])?.children || [];
    districtName = findNameById(districtOptions, value[2]);

    // 更新地址表单中的省市区名称
    addressForm.value.province = provinceName;
    addressForm.value.city = cityName;
    addressForm.value.district = districtName;
};

// 方法
const goBack = () => {
    router.go(-1)
}

const selectAddress = (address: UserAddressType) => {
    selectedAddress.value = address
}

const editAddress = (address: UserAddressType) => {
    editingAddress.value = address
    addressForm.value = { ...address }
    showAddressDialog.value = true
}
import { saveAddress as saveAddressApi } from '@/api/profile'
const saveAddress = () => {
    // 这里应该调用API保存地址
    saveAddressApi(addressForm.value)
    ElMessage.success('地址保存成功')
    showAddressDialog.value = false
    resetAddressForm()
}

const resetAddressForm = () => {
    addressForm.value = {
        id: 0,
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
    }
    selectedRegion.value = []
    editingAddress.value = null
}

const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (orderItems.value.length === 0) {
    ElMessage.warning('订单中没有商品')
    return
  }

  isSubmitting.value = true

  try {
    // 获取订单编号
    const orderNo = route.query.orderNo as string
    
    if (!orderNo) {
      ElMessage.error('缺少订单编号')
      return
    }

    // 构造订单更新数据
    const orderRenewData = {
      orderNo: orderNo,
      address: `${selectedAddress.value.province}${selectedAddress.value.city}${selectedAddress.value.district}${selectedAddress.value.detailAddress}`,
      phone: selectedAddress.value.receiverPhone,
      name: selectedAddress.value.receiverName,
      remark: ''
    }

    // 更新订单信息
    await orderApi.updateOrder(orderRenewData)

    // 从订单详情中获取优惠券ID列表
    const couponIds = orderDetail.value?.couponNames?.length ? 
      (orderDetail.value.couponIds || []) : []

    // 创建支付快照并跳转到支付页面
    const paymentData = {
      orderNo: orderNo,
      paymentMethod: 1, // 支付宝
      couponIds: couponIds, // 传递优惠券ID集合
      name: selectedAddress.value.receiverName,
      address: `${selectedAddress.value.province}${selectedAddress.value.city}${selectedAddress.value.district}${selectedAddress.value.detailAddress}`,
      phone: selectedAddress.value.receiverPhone,
      remark: ''
    }

    // 创建支付快照
    await payApi.createPayment(paymentData)
    
    ElMessage.success('订单提交成功')
    
    // 跳转到支付页面
    router.push(`/payment?orderNo=${orderNo}`)
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('订单提交失败')
  } finally {
    isSubmitting.value = false
  }
}

// 初始化数据
const initializeOrder = async () => {
    const orderNo = route.query.orderNo as string
    console.log('接收到的订单编号:', orderNo);

    try {
        if (orderNo) {
            // 根据订单编号获取订单详情
            console.log('开始获取订单详情...');
            const orderRes = await orderApi.getOrderDetail(orderNo)
            console.log('订单API响应:', orderRes);

            // 注意：实际数据在 orderRes.data 中
            const orderData = orderRes.data.data // 修改这里，正确访问 data 字段
            orderDetail.value = orderData

            // 如果订单详情中有couponIds，则获取对应的优惠券名称
            if (orderData.couponIds && orderData.couponIds.length > 0) {
                try {
                    // 创建一个获取所有优惠券详情的Promise数组
                    const couponPromises = orderData.couponIds.map((id:any) => 
                        promotionApi.getCouponById(id)
                    )
                    
                    // 并行获取所有优惠券详情
                    const couponResponses = await Promise.all(couponPromises)
                    
                    // 提取优惠券名称
                    const couponNames = couponResponses.map(response => response.data.data.name)
                    
                    // 将优惠券名称添加到orderDetail中
                    if (orderDetail.value) {
                        orderDetail.value.couponNames = couponNames
                    }
                    
                    // 计算优惠券折扣金额
                    // 首先需要获取商品信息用于计算折扣
                    const productsForDiscountCalc = orderData.productList.map((item: any) => ({
                        productId: item.id,
                        quantity: item.quantity || 1,
                        price: item.price
                    }))
                    
                    // 调用API计算最佳优惠券组合
                    const discountRes = await promotionApi.getBestDealCoupon(productsForDiscountCalc)
                    if (discountRes.data && discountRes.data.data) {
                        // 找到与当前使用的优惠券匹配的折扣信息
                        const matchingCoupon = discountRes.data.data.find((coupon: any) => {
                            // 检查coupon.ids中是否包含我们正在使用的优惠券ID
                            return orderData.couponIds.some((id: any) => coupon.ids.includes(id.toString()))
                        })
                        
                        if (matchingCoupon) {
                            // 将分转换为元（除以100）
                            couponDiscount.value = matchingCoupon.discountAmount / 100 || 0
                        }
                    }
                } catch (couponError) {
                    console.error('获取优惠券信息失败:', couponError)
                    ElMessage.warning('部分优惠券信息获取失败')
                }
            }

            // 处理商品列表，确保字段正确映射
            console.log('订单数据:', orderData);
            if (orderData && orderData.productList && Array.isArray(orderData.productList)) {
                console.log('商品列表:', orderData.productList);
                console.log('商品数量:', orderData.productList.length);

                if (orderData.productList.length > 0) {
                    orderItems.value = orderData.productList.map((item: any) => ({
                        productId: item.id,
                        name: item.name,
                        imageUrl: item.imageUrl,
                        price: item.price,
                        quantity: item.quantity || 1,
                        selected: true
                    }))
                    console.log('转换后的订单项:', orderItems.value);
                    ElMessage.success('订单信息加载成功')
                } else {
                    console.log('商品列表为空');
                    ElMessage.warning('订单中没有商品')
                    orderItems.value = []
                }
            } else {
                console.log('商品列表不存在或不是数组');
                console.log('实际数据结构:', typeof orderData.productList, orderData.productList);
                ElMessage.warning('订单中没有商品')
                orderItems.value = []
            }
        } else {
            console.log('缺少订单编号');
            ElMessage.error('缺少订单编号')
            router.push('/shoppingcart')
        }

        // 获取用户地址列表
        try {
            console.log('开始获取地址列表...');
            const addressRes = await getAddresses()
            console.log('地址API响应:', addressRes);
            console.log('地址列表:', addressRes.data.data);
            // 检查 addressRes.data 是否为数组
            if (Array.isArray(addressRes.data.data)) {
                // 验证每个地址元素的结构
                const validAddresses = addressRes.data.data.filter((addr: any) =>
                    addr.id !== undefined &&
                    addr.receiverName !== undefined &&
                    addr.receiverPhone !== undefined &&
                    addr.province !== undefined &&
                    addr.city !== undefined &&
                    addr.district !== undefined &&
                    addr.detailAddress !== undefined &&
                    addr.isDefault !== undefined
                );

                if (validAddresses.length > 0) {
                    addresses.value = validAddresses;
                } else {
                    console.error('地址数据结构不正确:', addressRes.data);
                    addresses.value = [];
                }
            } else {
                console.error('地址数据格式错误:', addressRes.data);
                addresses.value = []; // 设置为空数组，避免后续操作出错
            }

            // 设置默认地址
            if (Array.isArray(addresses.value)) { // 确保是数组再进行find操作
                const defaultAddress = addresses.value.find(addr => addr.isDefault);
                if (defaultAddress) {
                    selectedAddress.value = defaultAddress;
                } else if (addresses.value.length > 0) {
                    selectedAddress.value = addresses.value[0];
                }
            }
            console.log('地址列表加载完成');
        } catch (addressError) {
            console.error('获取地址信息失败:', addressError);
            ElMessage.warning('获取地址信息失败');
        }
    } catch (error) {
        console.error('获取订单信息失败:', error);
        ElMessage.error('获取订单信息失败: ' + (error as Error).message);
        router.push('/shoppingcart');
    }
}

onMounted(() => {
    initializeOrder()

    // 初始化地区数据
    getProvinces().then(res => {
        regionOptions.value = res.data.data.map((item: any) => ({
            id: item.id,
            name: item.name,
            children: []
        }));
    }).catch(() => {
        ElMessage.error('地区数据加载失败')
    })
})
</script>

<style scoped>
.order-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f8f8f8;
    min-height: 100vh;
}

.top-nav {
    padding: 15px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    align-items: center;
    gap: 15px;
    background-color: white;
    margin: -20px -20px 20px -20px;
    padding-left: 20px;
}

.welcome {
    font-size: 18px;
    color: #333;
    font-weight: 500;
}

.back-btn {
    padding: 5px 10px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.back-btn:hover {
    background-color: #e0e0e0;
}

.order-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.section-header h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
}

/* 地址部分样式 */
.address-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s;
}

.address-item:hover,
.address-item.active {
    border-color: #f56c6c;
    background-color: #fff5f5;
}

.address-main {
    margin-bottom: 5px;
}

.receiver {
    font-weight: bold;
    margin-right: 10px;
}

.phone {
    color: #666;
    margin-right: 10px;
}

.default-tag {
    background-color: #f56c6c;
    color: white;
    padding: 2px 5px;
    border-radius: 2px;
    font-size: 12px;
}

.address-detail {
    color: #666;
    font-size: 14px;
}

/* 商品部分样式 */
.product-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #eee;
}

.product-item:last-child {
    border-bottom: none;
}

.product-image {
    width: 80px;
    height: 80px;
    margin-right: 15px;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
}

.product-details {
    flex: 1;
}

.product-name {
    font-size: 16px;
    margin-bottom: 5px;
}

.product-price {
    color: #f56c6c;
    font-weight: bold;
}

.product-quantity {
    margin-right: 20px;
}

.product-subtotal {
    color: #f56c6c;
    font-weight: bold;
    min-width: 80px;
    text-align: right;
}

/* 订单总结部分样式 */
.order-summary {
    width: 300px;
    margin-left: auto;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
}

.summary-row.total {
    border-top: 1px solid #eee;
    margin-top: 10px;
    padding-top: 10px;
    font-weight: bold;
    font-size: 16px;
}

.total-price {
    color: #f56c6c;
    font-size: 18px;
}

/* 提交订单部分样式 */
.submit-section {
    display: flex;
    justify-content: flex-end;
    padding: 20px 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>